package cn.tianyigps.m7.factorys;


import cn.tianyigps.m7.beans.Equipment;
import cn.tianyigps.m7.beans.M7;
import cn.tianyigps.m7.cache.ChannelCache;
import cn.tianyigps.m7.netty.LengthFieldBasedFrameDecoder;
import cn.tianyigps.m7.netty.TYChannelPipeline;
import cn.tianyigps.m7.utils.MessageCoding;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.StringUtil;

import java.util.List;

/**
 * Created with IDEA
 *
 * @description: 设备和型号路由
 * @author: cui.guibin
 * @create: 2019/3/7 11:05
 **/
public class EquipmentFactory {

    /**
     * @param: data
     * @return Equipment
     * @author cui.guibin
     * @date 2019/3/7 11:17
     * 根据 设备起始位和特定标识 判断型号
     */
    public static Equipment equipmentInstance(ChannelHandlerContext ctx, String data){

        TYChannelPipeline pipeline = (TYChannelPipeline) ctx.pipeline();
        if (StringUtil.isNullOrEmpty(data)) {
            return null;
        }
        String packType = M7.getPackType(data);
        //登陆包保存设备号
        String equipmentId = null;
        if ("787801".equals(packType)) {
            equipmentId = data.substring(8,24).replaceFirst("^0*", "");
        }
        Equipment equipment = null;
        if (!StringUtil.isNullOrEmpty(equipmentId)) {
            equipment = new M7(equipmentId, "m7");
            pipeline.setEquipment(equipment);
            ChannelCache<String, ChannelHandlerContext> instance = ChannelCache.getInstance();
            instance.put(equipment.getEquipmentId(), ctx);
        }

        return equipment;
    }
    /**
     * @param: data
     * @return Equipment
     * @author cui.guibin
     * @date 2019/3/7 11:17
     * 根据 设备初始化 设备号和型号
     */
    public static void initPipeline(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list){
        try {
            ByteBuf buf = byteBuf.copy();
            String strData = MessageCoding.getHexStr(buf);
            if (strData.startsWith("7878")) {
                new LengthFieldBasedFrameDecoder(65536, 2, 1, 2, 0).decode(ctx, byteBuf, list);
            }else if (strData.startsWith("7979")){
                new LengthFieldBasedFrameDecoder(65536, 2, 2, 2, 0).decode(ctx, byteBuf, list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
